package com.mineoj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.constant.CommonConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.mapper.NoticeReadMapper;
import com.mineoj.model.dto.notice.NoticeQueryRequest;
import com.mineoj.model.entity.*;
import com.mineoj.model.vo.NoticeVO;
import com.mineoj.model.vo.UserVO;
import com.mineoj.service.NoticeService;
import com.mineoj.mapper.NoticeMapper;
import com.mineoj.service.UserService;
import com.mineoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 明月
* @description 针对表【notice(公告)】的数据库操作Service实现
* @createDate 2025-04-12 22:54:58
*/
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
    implements NoticeService{
    @Resource
    private UserService userService;

    @Resource
    private NoticeReadMapper noticeReadMapper;



    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 校验
     * @param notice 要校验的帖子
     * @param add
     */
    @Override
    public void validNotice(Notice notice, boolean add) {
        if (notice == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = notice.getTitle();
        String content = notice.getContent();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param noticeQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Notice> getQueryWrapper(NoticeQueryRequest noticeQueryRequest) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        if (noticeQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = noticeQueryRequest.getSearchText();
        String sortField = noticeQueryRequest.getSortField();
        String sortOrder = noticeQueryRequest.getSortOrder();
        Long id = noticeQueryRequest.getId();
        String title = noticeQueryRequest.getTitle();
        String content = noticeQueryRequest.getContent();
        Long userId = noticeQueryRequest.getUserId();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public NoticeVO getNoticeVO(Notice notice, HttpServletRequest request) {
        NoticeVO noticeVO = NoticeVO.objToVo(notice);
        long noticeId = notice.getId();
        // 1. 关联查询用户信息
        Long userId = notice.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        noticeVO.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            // 获取已读
            QueryWrapper<NoticeRead> noticeReadQueryWrapper = new QueryWrapper<>();
            noticeReadQueryWrapper.in("noticeId", noticeId);
            noticeReadQueryWrapper.eq("userId", loginUser.getId());
            NoticeRead noticeRead = noticeReadMapper.selectOne(noticeReadQueryWrapper);
            noticeVO.setHasRead(noticeRead != null);

        }
        return noticeVO;
    }

    @Override
    public Page<NoticeVO> getNoticeVOPage(Page<Notice> noticePage, HttpServletRequest request) {
        List<Notice> noticeList = noticePage.getRecords();
        Page<NoticeVO> noticeVOPage = new Page<>(noticePage.getCurrent(), noticePage.getSize(), noticePage.getTotal());
        if (CollUtil.isEmpty(noticeList)) {
            return noticeVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = noticeList.stream().map(Notice::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> noticeIdHasReadMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            Set<Long> noticeIdSet = noticeList.stream().map(Notice::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);
            // 获取已读
            QueryWrapper<NoticeRead> noticeReadQueryWrapper = new QueryWrapper<>();
            noticeReadQueryWrapper.in("noticeId", noticeIdSet);
            noticeReadQueryWrapper.eq("userId", loginUser.getId());
            List<NoticeRead> noticeNoticeReadList = noticeReadMapper.selectList(noticeReadQueryWrapper);
            noticeNoticeReadList.forEach(noticeNoticeRead -> noticeIdHasReadMap.put(noticeNoticeRead.getNoticeId(), true));
        }
        // 填充信息
        List<NoticeVO> noticeVOList = noticeList.stream().map(notice -> {
            NoticeVO noticeVO = NoticeVO.objToVo(notice);
            Long userId = notice.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            noticeVO.setUser(userService.getUserVO(user));
            noticeVO.setHasRead(noticeIdHasReadMap.getOrDefault(notice.getId(), false));
            return noticeVO;
        }).collect(Collectors.toList());
        noticeVOPage.setRecords(noticeVOList);
        return noticeVOPage;
    }

}




